import json
import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import Optional, Any, List, Dict

logger = logging.getLogger(__name__)

API_CONFIG_FILE_PATH = os.path.join(
    os.path.dirname(__file__),
    "config",
    "dwf_apis.json"
)


class APIType(str, Enum):
    APP = 'app'
    MODELER = 'modeler'


@dataclass
class DWFConfig:
    """DWF实例配置"""
    host: str
    modeler_port: int = 6060
    app_port: int = 9090
    username: str = ""
    password: str = ""

    def get_base_url(self, api_type: str = APIType.APP) -> str:
        """根据API类型获取基础URL"""
        port = self.app_port if api_type == 'app' else self.modeler_port
        return f"{self.host}:{port}"


class DWFAPIDefinition:
    """DWF API定义类，用于描述每个API的元信息"""

    def __init__(self, config: Dict[str, Any]):
        """从配置字典初始化API定义"""
        self.name = config['name']
        self.group = config.get('group', '')
        self.type = config.get('type', 'app')
        self.method = config['method']
        self.url_template = config['url_template']
        self.description = config['description']
        self.parameters = config.get('parameters', [])
        self.headers = config.get('headers', [])
        self.query_params = config.get('query_params', [])
        self.body_params = config.get('body_params', [])
        self.returns = config.get('returns', "")
        self.examples = config.get('examples', [])

    @classmethod
    def from_dict(cls, config: Dict[str, Any]) -> 'DWFAPIDefinition':
        """从字典创建API定义"""
        return cls(config)

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            'name': self.name,
            'group': self.group,
            'type': self.type,
            'method': self.method,
            'url_template': self.url_template,
            'description': self.description,
            'parameters': self.parameters,
            'headers': self.headers,
            'query_params': self.query_params,
            'body_params': self.body_params,
            'returns': self.returns,
            'examples': self.examples
        }

    def get_full_description(self) -> str:
        """获取完整的API描述，包含返回值、示例等信息"""
        desc_parts = [f'    """{self.description}']

        # 添加参数说明
        if self.parameters:
            desc_parts.append("\n    Args:")
            for param in self.parameters:
                param_desc = f"        {param['name']}: {param.get('description', '')}"
                desc_parts.append(param_desc)

        # 添加返回值说明
        if self.returns:
            desc_parts.append(f"\n    Returns:")
            desc_parts.append(f"        {self.returns}")

        # 添加示例
        if self.examples:
            desc_parts.append(f"\n    Examples:")
            # examples现在是列表形式
            for example in self.examples:
                if example.strip():
                    desc_parts.append(f"        {example.strip()}")

        desc_parts.append('    """')
        return "\n".join(desc_parts)


class DWFAPIManager:
    """DWF API管理器，用于加载、管理和提供API定义"""

    def __init__(self, api_config_file: str = None):
        """
        初始化API管理器

        Args:
            api_config_file: API配置文件路径
        """
        self.api_config_file = API_CONFIG_FILE_PATH
        if api_config_file:
            self.api_config_file = api_config_file
        self.apis: Dict[str, DWFAPIDefinition] = {}
        self.load_apis()

    def load_apis(self) -> None:
        """从配置文件加载API定义"""
        if not os.path.exists(self.api_config_file):
            raise FileNotFoundError(f"API config file not found: {self.api_config_file}")

        with open(self.api_config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)

        # 支持两种格式：列表格式和对象格式
        if isinstance(config, list):
            apis_data = config
        else:
            apis_data = config.get('apis', [])

        self.apis.clear()

        for api_config in apis_data:
            try:
                api_def = DWFAPIDefinition.from_dict(api_config)
                self.apis[api_def.name] = api_def
            except Exception as e:
                logger.warning(f"skip invalid APIDefinition {api_config.get('name', 'unknown')}: {e}")

    def list_apis(self,
                  group: Optional[str] = None,
                  api_type: Optional[str] = None,
                  method: Optional[str] = None) -> List[DWFAPIDefinition]:
        """
        列出API定义

        Args:
            group: 按分组过滤 (entity, meta, etc.)
            api_type: 按类型过滤 (app, modeler)
            method: 按HTTP方法过滤

        Returns:
            DWFAPIDefinition列表
        """
        filtered_apis = []

        for api_def in self.apis.values():
            # 应用过滤条件
            if group and api_def.group != group:
                continue
            if api_type and api_def.type != api_type:
                continue
            if method and api_def.method.upper() != method.upper():
                continue

            filtered_apis.append(api_def)

        return filtered_apis